import { login } from "../../api/userApi";
import { ElMessage, ElMessageBox } from "element-plus";
import store from "..";
export default {
  namespaced: true,
  state: () => {
    return {
      userinfo: [],
      token: localStorage.getItem("token") || "",
    };
  },
  mutations: {
    //修改token
    setToken(state, val) {
      state.token = val;
    },
    //修改用户信息
    setUser(state, val) {
      state.userinfo = val;
    },
  },
  actions: {
    //登录
    async handleLogin(context, params) {
      let res = await login(params);
      return new Promise((resolve, reject) => {
        if (res) {
          // @ts-ignore
          context.commit("setToken", res.token);
          // @ts-ignore
          localStorage.setItem("token", res.token);
          resolve(true);
        }
        reject(false);
      });
    },
    //退出登录
    handleLogOut(context) {
      ElMessageBox.confirm("请问你确定要退出登录吗?", "退出登录", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          context.commit("setToken", "");
          localStorage.removeItem("token");
          context.commit("setUser", {});
          store.commit('cart/setCart',[])
          ElMessage({
            type: "success",
            message: "退出成功",
          });
        })
        .catch(() => {});
    },
  },
};
